package com.example.weather_app.core;

import android.content.Context;
import android.content.res.Resources;

import com.example.weather_app.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class CitySearch {
    private final Map<String, String> cityIdMap = new HashMap<>();

    // 构造函数：传入 Context 用于获取 Resources
    public CitySearch(Context context) {
        loadDataFromRaw(context);
    }

    // 从 res/raw 目录加载数据
    private void loadDataFromRaw(Context context) {
        try (InputStream is = context.getResources().openRawResource(R.raw.city_data);
             BufferedReader br = new BufferedReader(new InputStreamReader(is))) {

            String line;
            while ((line = br.readLine()) != null) {
                processLine(line.trim());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 处理单行数据（城市:ID格式）
    private void processLine(String line) {
        if (line.isEmpty() || !line.contains(":")) return;
        String[] parts = line.split(":", 2);
        if (parts.length == 2) {
            cityIdMap.put(parts[0].trim(), parts[1].trim());
        }
    }

    // 查询城市 ID
    public String getCityId(String cityName) {
        return cityIdMap.getOrDefault(cityName, "未找到该城市ID");
    }
}